import Taro, {Component} from '@tarojs/taro'
import { View, Button, Image } from '@tarojs/components'

export default class List extends Component {
  constructor (props) {
    super(props)
    this.state = {
      goods: []
    }
  }
  componentDidMount () {
    this.getGoodList()
  }

  getGoodList = () => {
    const db = wx.cloud.database();
    db.collection('goods').get().then((res) => {
      this.setState({
        goods: res.data || []
      })
    });
  }

  handleGoodClick = (id) => {

  }

  makeOrder = (id) => {
    //console.log(id)
    Taro.showLoading({ title: ' ',
    });
    console.log(id)
    wx.cloud.callFunction({
      name: 'pay',
      data: {
        type: 'unifiedorder',
        data: {
          goodId: id
        }
      }
    }).then((res) => {
      //res.data
      console.log(res.result)
      console.log(res.result.data.out_trade_no)
      Taro.navigateTo({
        url: `/pages/index/result/index?id=${res.result.data.out_trade_no}`
      });
    });
    Taro.hideLoading();
  }
  render() {
    if (this.state.goods.length === 0) {
      return null
    }
    return (
      <View class="container">
        {
          this.state.goods.map((item, index) => {
            return (
              <View key={index} className="good-item" onClick={this.handleGoodClick.bind(this, item._id)}>
                <View className="good-image">
                  <Image src={item.pic} />
                </View>
                <View className="good-detail">
                  <View className="title">商品: {item.name}</View>
                  <View className="content">价格： {item.price / 100} 元 </View>
                  <Button
                    type="primary"
                    onClick={this.makeOrder.bind(this, item._id)}
                  >下单</Button>
                </View>
              </View>
            )
          })
        }

      </View>
    );
  }
}
